package com.nelson.android.ndk

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

/**
 * [Android NDK开发入门](https://segmentfault.com/a/1190000037594523)
 */
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Example of a call to a native method
        findViewById<TextView>(R.id.sample_text).text = stringFromJNI()

        findViewById<Button>(R.id.btn_str).setOnClickListener {
            val result = operateString("待操作的字符串")
            Log.e(TAG, result)
            Toast.makeText(this, result, Toast.LENGTH_SHORT).show()
        }

        findViewById<Button>(R.id.btn_array).setOnClickListener {
            val array = intArrayOf(1, 2, 3)
            val result = sumArray(array)
            Log.e(TAG, result.toString())
            Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show()
        }

        findViewById<Button>(R.id.btn_array2).setOnClickListener {
            val array = intArrayOf(1, 2, 3)
            val result = sumArray2(array)
            Log.e(TAG, result.toString())
            // native 层修改了数组元素，这种方式很危险！！！
            Log.e(TAG, array.sum().toString())
            Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show()
        }

        findViewById<Button>(R.id.btn_array_obj).setOnClickListener {
            val init2DArray = init2DArray(3)
        }

        findViewById<Button>(R.id.btn_call_static_method).setOnClickListener {
            callJavaStaticMethod()
        }

        findViewById<Button>(R.id.btn_call_instance_method).setOnClickListener {
            callJavaInstanceMethod()
        }

        findViewById<Button>(R.id.btn_native_crash_test).setOnClickListener {
            nativeCrashTest()
        }
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    // 1.Google Android NDK example
    external fun stringFromJNI(): String

    // native 操作 JVM
    // 2.字符串操作示例
    external fun operateString(str: String): String

    // 3.数组操作
    external fun sumArray(array: IntArray): Int
    external fun sumArray2(array: IntArray): Int

    // 4.对象数组-在 native 层创建一个二维数组，且赋值并返回给 Java 层使用
    external fun init2DArray(size: Int): Array<IntArray>

    // 5. native 层调用 Java 静态方法
    external fun callJavaStaticMethod()

    // 6. native 调用 Java 实例方法
    external fun callJavaInstanceMethod()

    // 7. NDK 错误定位
    external fun nativeCrashTest()

    companion object {
        private const val TAG = "MainActivity"

        // Used to load the 'native-lib' library on application startup.
        init {
            System.loadLibrary("native-lib")
        }
    }
}